<template>
  <!-- 管理员 ==> 人员管理 页面  -->
  <view>
    <!--选项卡： 维修人员信息管理，业主信息管理 -->
    <view>
      <u-subsection :list="xuanXiangList" mode="subsection" :current="subCurrent" @change="xuanXiangChange">
      </u-subsection>
    </view>

    <!-- <uni-card > -->
    <view>
      <!-- 顶部按钮  新增  编辑  删除  模糊查询-->
      <view style="display: flex;
                  justify-content: space-around;
                  margin-top: 10rpx;">
        <!-- 新增 -->
        <view><button @click="addPeople" type="primary" size="mini">新增</button></view>
        <!-- 编辑 -->
        <view><button @click="editPeople" type="primary" size="mini">编辑</button></view>
        <!-- 删除 -->
        <view><button @click="deletePeople" type="warn" size="mini">删除</button></view>
        <!-- 确认删除 弹框 -->
        <view>
          <u-modal :show="delConfirmshow" :title="title" showCancelButton="true"
            :content="'您确定要删除 <'+ checkedArr[0].name +'> 的信息吗？'" :closeOnClickOverlay="true" @confirm="confirm"
            @cancel="cancel" @close="close1"></u-modal>
        </view>
        <!-- 模糊查询 -->
        <view><button @click="selectPeople" type="primary" size="mini">查询</button></view>
        <!-- 查询弹窗  box  -->
        <view>
          <u-popup :show="showQuery" :overlay="true" :closeOnClickOverlay="true" :closeable="true" :round="10"
            mode="center" @close="close" @open="open">
            <!-- 查询内容box -->
            <view style="width: 100%;" :style="{height: wh + 50 + 'px'}">
              <!-- 整个box -->
              <view class="box" style="margin-top: 150rpx;">
                <!-- 查询条件信息 -->
                <view class="box2" style="width: 600rpx;">
                  <view style="font-size: large;font-weight: bold;color: #6A6A6A;">按姓名模糊查询</view>
                  <view style="border-bottom: 2rpx solid #c1c1c0;">
                    <view class="text" style="width: 150rpx;">关键字：</view>
                    <view class="input"><input type="text" name="nameKey" v-model="nameKey" placeholder="请输入姓名关键字" /></view>
                    <!-- <view class="input" >
                    </view> -->
                  </view>
                </view>
                <view @click="querySubmit" class="submit" style="background-color:#E43D33;margin-top: 200rpx;">查询</view>
              </view>
            </view>
          </u-popup>
        </view>
      </view>
      <!-- 表格 -->
      <view :style="{height: wh + 'px'}">
        <!--zb-table的属性  :pullUpLoading="pullUpLoadingAction" :isShowLoadMore="true" -->
        <zb-table @sort-change="sortChange" ref="zbTable" :summary-method="getSummaries" :highlight="true"
          :show-header="true" :columns="column" :fit="false" row-key="id" @rowClick="rowClick"
          @toggleRowSelection="toggleRowSelection" @toggleAllSelection="toggleAllSelection" :border="true"
          @custom="custom" @edit="buttonEdit" @dele="dele" :data="data"></zb-table>
      </view>
    </view>
    <!-- </uni-card> -->
    <!-- 弹出层box  新增，编辑 -->
    <view>
      <u-popup :show="addeditShow" :overlay="true" :closeOnClickOverlay="true" :closeable="true" :round="10"
        mode="bottom" @close="close" @open="open">
        <!-- 弹出内容box -->
        <scroll-view class="" scroll-y :style="{height: wh + 120 + 'px'}">
          <view style="width: 100%;" :style="{height: wh + 120 + 'px'}">
            <!-- 整个box -->
            <view class="box">
              <!-- 人员信息 -->
              <view class="box2">
                <view style="font-size: large;font-weight: bold;color: #6A6A6A;">{{subCurrent===0?'维修人员':'业主'}}信息</view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">姓名：</view>
                  <view class="input"><input type="text" name="name" v-model="name" placeholder="请输入姓名" /></view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">性别：</view>
                  <view class="input">
                    <radio-group @change="radioChange">
                      <label class="radio">
                        <radio value="男" checked="true" />男
                      </label>
                      <label class="radio">
                        <radio value="女" />女
                      </label>
                    </radio-group>
                  </view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">年龄：</view>
                  <view class="input"><input type="text" name="age" v-model="age" placeholder="请输入年龄" /></view>
                </view>
                <view>
                  <view class="text">照片：</view>
                  <view>
                    <u-upload :fileList="fileList3" @afterRead="afterRead" @delete="deletePic" name="3" multiple
                      :maxCount="1"></u-upload>
                  </view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">地址：</view>
                  <view class="input"><input type="text" name="address" v-model="address" placeholder="请输入地址" /></view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">电话：</view>
                  <view class="input"><input type="text" name="tel" v-model="tel" placeholder="请输入电话" /></view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">账号：</view>
                  <view class="input"><input type="text" name="username" v-model="username" placeholder="请输入账号" />
                  </view>
                </view>
                <view style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">密码：</view>
                  <view class="input"><input type="text" name="password" v-model="password" placeholder="请输入密码" />
                  </view>
                </view>
                <view v-if="subCurrent===0" style="border-bottom: 2rpx solid #c1c1c0;">
                  <view class="text">员工状态：</view>
                  <view class="input"><input type="text" name="status" v-model="status" placeholder="请输入员工状态" /></view>
                </view>

              </view>
              <view v-if="btnname === '新增'" @click="btnadd" class="submit" style="">新增</view>
              <view v-if="btnname === '编辑'" @click="btnedit" class="submit" style="">保存</view>
            </view>
          </view>
        </scroll-view>
      </u-popup>

    </view>
    <!-- 自定义tabBar -->
    <view>
      <u-tabbar :value="tabBarIndex" :fixed="true" @change="tabBarchange" :placeholder="false" activeColor="#1296db"
        :safeAreaInsetBottom="false">
        <block v-for="(item,index) in tabBarList" :key="index">
          <u-tabbar-item :text="item.text">
            <image class="u-page__item__slot-icon" slot="inactive-icon" :src="item.iconPath"></image>
            <image class="u-page__item__slot-icon" slot="active-icon" :src="item.selectedIconPath"></image>
          </u-tabbar-item>
        </block>
      </u-tabbar>
    </view>
  </view>
</template>

<script>
  //获取应用实例
  const app = getApp()
  // 按需导入 mapState ,mapMutations,mapGetters 辅助函数
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    data() {
      return {
        // 窗口的可用高度 = 屏幕高度 - navigationBar高度 - tabBar 高度
        wh: 0,
        subCurrent: 0, //维修人员管理，业主信息管理
        xuanXiangList: ['维修人员管理', '业主信息管理'],
        // 确认删除弹框 
        delConfirmshow: false,
        // 编辑  底部弹出show
        addeditShow: false,
        showQuery:false,//查询弹窗
        nameKey:'',//按姓名查询  关键字
        btnname: '新增',
        column: [],
        data: [],
        ownerData: [],
        workerData: [],
        checkedArr: [], //选中的项  数组
        flag1: true,
        flag2: true,
        num: 0,
        num1: 0,
        isShowLoadMore: true,
        // 信息
        id: 0,
        name: '',
        sex: '男',
        age: 0,
        // imgurl:'',
        fileList3: [],
        address: '',
        tel: '',
        username: '',
        password: '',
        status: '',
        // 是否正在请求数据    节流阀（防止短时间内重复请求）
        isloading: false,
        // usertype:'',

      };
    },
    onLoad(option) {
      this.getWorkerData();//获取维修人员信息
      this.getOwnerData();//获取业主信息
      // 获取当前系统的信息
      const sysInfo = uni.getSystemInfoSync()
      // 为 wh 窗口可用高度动态赋值   可用高度 = 屏幕高度 - navigationBar高度 - tabBar高度 - 自定义的search组件高度
      this.wh = sysInfo.windowHeight - 145
      setTimeout(() => {
        if(option.subCurrent+''==='0'||option.subCurrent+''==='undefined'){
          this.subCurrent=0;
          this.column = this.workercolumn;
          this.data = this.workerData;
        }else{
          this.subCurrent=1;
          this.column = this.usercolumn;
          this.data = this.ownerData;
        }
      }, 1000)
    },
    computed: {
      // 将 m_user 模块中的 userType 数据映射到当前页面中使用
      ...mapState('m_user', ['userType', 'tabBarList1', 'tabBarList2', 'tabBarList3', 'workercolumn', 'usercolumn', ]),
      ...mapState('m_tabbar', ['tabBarList', 'tabBarIndex']),
    },
    methods: {
      // 选择 维修人员管理 or 业主信息管理
      xuanXiangChange(index) {
        this.subCurrent = index;
        if (this.subCurrent === 0) {
          this.column = this.workercolumn;
          this.data = this.workerData;
        } else {
          this.column = this.usercolumn;
          this.data = this.ownerData;
        }

      },
      async getWorkerData(cb) {
        // ** 打开节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/user/getworkerlist')
        // ** 关闭节流阀
        this.isloading = false
        // 只要数据请求完毕，就立即按需调用 cb 回调函数,cb() 是关闭下拉刷新的
        cb && cb()
        if (res.status !== 200) return uni.$showMsg()
        this.workerData = res.data;
      },
      async getOwnerData(cb) {
        // ** 打开节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/user/getownerlist')
        // ** 关闭节流阀
        this.isloading = false
        // 只要数据请求完毕，就立即按需调用 cb 回调函数,cb() 是关闭下拉刷新的
        cb && cb()
        if (res.status !== 200) return uni.$showMsg()
        this.ownerData = res.data;
      },
      // 下拉刷新的事件
      onPullDownRefresh() {
        // 1. 重置关键数据
        this.isloading = false
        this.workerData = [];
        this.ownerData = [];
        // 2. 重新发起请求   传参（关闭下拉刷新，因为默认不关闭）
        this.getWorkerData(() => uni.stopPullDownRefresh())
        this.getOwnerData(() => uni.stopPullDownRefresh())
      },

      // 表格相关的事件
      sortChange(item, sorterMode, index) {

        console.log('触发排序', item, sorterMode, index)
      },
      cellStyle({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        // console.log('row, column, rowIndex, columnIndex')
        if (columnIndex === 1 || columnIndex === 4) {
          return {
            color: 'red'
          }
        }
      },
      // pullUpLoading(done) {
      //   if (!this.flag1) {
      //     return
      //   }
      //   setTimeout(() => {
      //     this.data.push({
      //       date: '2011-05-02',
      //       name: '王小虎23',
      //       province: '上海',
      //       sex: 1,
      //       price: 33,
      //       id: 11111 + this.num,
      //       age: '30',
      //       city: '普陀区',
      //       address: '上海市普',
      //       zip: 200333
      //     })

      //     this.num++
      //     if (this.num === 3) {
      //       done('ok')
      //       this.flag1 = false
      //     } else {
      //       done()
      //     }
      //   }, 2000)
      // },

      // pullUpLoadingAction(done) {
      //   console.log(this.flag2)
      //   if (!this.flag2) {
      //     return
      //   }
      //   setTimeout(() => {
      //     this.data.push({
      //       date: '2011-05-02',
      //       name: '王小虎23',
      //       province: '上海',
      //       sex: 1,
      //       price: 33,
      //       id: "11111",
      //       age: '30',
      //       city: '普陀区',
      //       address: '上海市普',
      //       zip: 200333
      //     })

      //     this.num1++
      //     if (this.num1 === 3) {
      //       this.$refs.zbTable.pullUpCompleteLoading('ok')
      //       this.flag2 = false
      //     } else {
      //       this.$refs.zbTable.pullUpCompleteLoading()
      //     }
      //   }, 1000)
      // },
      buttonEdit(ite, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击编辑'
        })
        console.log(ite, index)
      },
      dele(ite, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击删除'
        })
        // alert('点击删除')
        console.log(ite, index)
      },
      custom() {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击自定义'
        })
      },
      toggleAllSelection(checked, arr) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击全选'
        })
        console.log('全选', checked, arr)
        this.checkedArr = arr;
      },
      toggleRowSelection(checked, arr) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '点击单选'
        })
        console.log('单选', checked, arr)
        this.checkedArr = arr;
      },
      currentChange(row, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '选中当前一行'
        })
        console.log('单选', row, index)
      },
      rowClick(row, index) {
        uni.showToast({
          icon: 'none',
          duration: 3000,
          title: '单击某行'
        })
        console.log('单击某行', row, index)
      },
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总价';
            return;
          }
          if (column.name === 'price') {
            const values = data.map(item => Number(item[column.name]));
            if (!values.every(value => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index] += ' 元';
            }
          } else {
            sums[index] = 'N/A';
          }
        });
        return sums;
      },
      // 新增
      addPeople() {
        this.btnname = '新增';
        this.addeditShow = true;
      },
      // 编辑
      editPeople() {
        if (this.checkedArr.length !== 1) {
          uni.$showMsg("只能选中一项进行编辑！");
        } else {
          this.btnname = '编辑';
          this.name = this.checkedArr[0].name;
          this.sex = this.checkedArr[0].sex;
          this.age = this.checkedArr[0].age;
          // user.img=this.fileList3[0];
          // user.img = '',
          var imgurl = {};
          imgurl.url = this.checkedArr[0].img;
          this.fileList3[0] = imgurl;
          this.address = this.checkedArr[0].address;
          this.tel=this.checkedArr[0].tel;
          this.username = this.checkedArr[0].username;
          this.password = this.checkedArr[0].password;
          if(this.subCurrent===0){
            this.status = this.checkedArr[0].status;
            // this.usertype='维修人员'
          }else{
            // this.usertype='业主'
          }
          this.addeditShow = true;
        }
      },
      // 删除
      deletePeople() {
        if (this.checkedArr.length < 1) {
          uni.$showMsg("至少选中一项进行删除！");
        } else {
          this.delConfirmshow = true;
        }
      },
      // 确认删除弹框  确认按钮单击事件
      async confirm() {
        const {data: res} = await uni.$http.delete('/user/deleteuser',this.checkedArr)
         if (res.status !== 200) return uni.$showMsg("删除失败")
         else{
           uni.$showMsg("删除成功")
           setTimeout(()=>{
             uni.redirectTo({
             	url: '/pages/admin-people/admin-people?subCurrent='+this.subCurrent
             });
           },1000)
           this.checkedArr.pop();
           this.delConfirmshow = false;
           console.log("删除成功")
         }
      },
      // 确认删除弹框  取消按钮单击事件
      cancel() {
        this.delConfirmshow = false;
      },
      // 确认删除弹框  关闭按钮单击事件
      close1() {
        this.delConfirmshow = false;
      },
      // 查询
      selectPeople() {
        this.showQuery=true;
      },
      // 底部弹出的新增，编辑   打开事件
      open() {
        // console.log('open');
      },
      // 底部弹出的新增，编辑   关闭事件
      close() {
        this.showQuery = false;
        this.addeditShow = false;
      },
      // 弹出层 btn新增
      async btnadd() {
        if(this.name==='' || this.sex==='' || this.age==='0'|| this.username==='' || this.password===''){
          return uni.$showMsg("姓名、性别、年龄、账号、密码不能为空！")
        }
        var user = {};
        // user.id=   数据库里面是自增字段，存入数据库时，这个设置为  null 即可
        user.name = this.name;
        user.sex = this.sex;
        user.age = this.age;
        if(this.fileList3.length>0){
          user.img=this.fileList3[0].url+'';
        }
        console.log(user.img)
        user.checked = false;
        user.address = this.address;
        user.tel = this.tel;
        user.username = this.username;
        user.password = this.password;
        if (this.subCurrent === 0) {
          user.status = this.status;
          user.usertype='维修人员';
        }else{
          user.usertype='业主';
        }
        const {
          data: res
        } = await uni.$http.post('/user/adduser', user)
        if (res.status !== 200) return uni.$showMsg("新增失败")
        else {
          uni.$showMsg("新增成功")
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/admin-people/admin-people?subCurrent='+this.subCurrent
            });
          }, 1000)
        }
        // this.data.push(user);
        this.close();
      },
      // 弹出层 btn保存
      async btnedit() {
        var user = {};
        user.id = this.checkedArr[0].id;
        user.name = this.name;
        user.sex = this.sex;
        user.age = this.age;
        if(this.fileList3.length>0){
          user.img=this.fileList3[0].url+'';
        }
        user.checked = false;
        user.address = this.address;
        user.username = this.username;
        user.password = this.password;
        if (this.subCurrent === 0) {
          user.status = this.status;
          user.usertype='维修人员';
        }else{
          user.usertype='业主';
        }
        const {data: res} = await uni.$http.put('/user/updateuser', user)
        if (res.status !== 200) return uni.$showMsg("修改失败")
        else {
          uni.$showMsg("修改成功")
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/admin-people/admin-people?subCurrent='+this.subCurrent
            });
          }, 1000)
          this.checkedArr.pop();
          this.close();
        }
      },
      //弹窗  查询按钮
      async querySubmit(){
        if(this.subCurrent==0){//维修人员管理
          let nameKey = this.nameKey;
          console.log("querySubmit==========>>>>>>>nameKey")
          console.log(nameKey);
          const {data: res} = await uni.$http.get('/user/getWorkerLikeName',{"nameKey":nameKey})
          if (res.status !== 200) return uni.$showMsg()
          this.data=res.data;
          this.showQuery=false;
        }else if(this.subCurrent==1){//业主管理
          let nameKey = this.nameKey;
          console.log("querySubmit==========>>>>>>>nameKey")
          console.log(nameKey);
          const {data: res} = await uni.$http.get('/user/getOwnerLikeName',{"nameKey":nameKey})
          if (res.status !== 200) return uni.$showMsg()
          this.data=res.data;
          this.showQuery=false;
        }
      },
      radioChange(e) {
        this.sex = e.detail.value;
      },
      // 删除图片
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1)
      },
      // 新增图片
      async afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        console.log(event.name)
        let lists = [].concat(event.file)
        let fileListLen = this[`fileList${event.name}`].length
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this[`fileList${event.name}`][fileListLen]
          this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: result
          }))
          fileListLen++
        }
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: app.globalData.baseUrl+'/qiniu/testUpload', // Spring Boot接口地址
            filePath: url,
            name: 'file',
            formData: {
              user: 'test'
            },
            success: (res) => {
              setTimeout(() => {
                resolve(res.data)
              }, 1000)
            }
          });
        })
      },


      // tabbar
      ...mapMutations('m_tabbar', ['updateTabBarList', 'updateTabBarIndex']),
      tabBarchange(name) {
        // uni.switchTab({
        //   url: this.tabBarList[name].pagePath
        // })
        uni.redirectTo({
          url: this.tabBarList[name].pagePath
        })
        this.setTabBarIndex(name);
      },
      setTabBarIndex(index) {
        this.updateTabBarIndex(index);
      }
    }
  }
</script>

<style lang="scss">
  ::v-deep {
    .uni-card {
      margin: 8px !important;
      padding: 0 !important;

      .uni-card__content {
        padding: 0 !important;
      }
    }
  }

  .box {
    padding: 30rpx;
  }

  .box1,
  .box2 {
    // border-radius: 30rpx;
    margin-bottom: 30rpx;
    padding: 25rpx;
    box-shadow: 0 0 15rpx #999999
  }

  .box1>view,
  .box2>view {
    padding: 10rpx;
    display: flex;
    margin-bottom: 10rpx;
    font-family: Microsoft YaHei;

    color: #333333;
  }

  .text {
    width: 30%;
    text-align: left;
    overflow: auto;
  }


  .submit {
    background-color: #1599FD;
    color: #FFFFFF;
    font-weight: bold;
    text-align: center;
    border-radius: 15rpx;
    line-height: 100rpx;
    height: 100rpx;
  }

  // tabbar
  .u-page {
    padding: 0;

    &__item {

      &__title {
        color: $u-tips-color;
        background-color: $u-bg-color;
        padding: 30rpx;
        font-size: 30rpx;

        &__slot-title {
          color: $u-primary;
          font-size: 30rpx;
        }
      }

      &__slot-icon {
        width: 70rpx;
        height: 70rpx;
      }
    }
  }
</style>
